import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutterstudyapplast/business/viewmodels/article_collect_viwemodel.dart';
import 'package:flutterstudyapplast/common/event/events.dart';
import 'package:flutterstudyapplast/manager/app_manager.dart';
import 'package:flutterstudyapplast/services/service_locator.dart';
import 'package:flutterstudyapplast/ui/page/page_login.dart';
import 'package:webview_flutter/webview_flutter.dart';

class WebViewPage extends StatefulWidget {
  final webData;
  ///是否允许被收藏
  final isCanCollect;

  WebViewPage(this.webData, {this.isCanCollect = false});

  @override
  _WebViewPageState createState() => _WebViewPageState();
}

class _WebViewPageState extends State<WebViewPage> {
  bool isLoading = true;
  WebViewController _webViewController;
  JavascriptChannel _JsBridge(BuildContext context) => JavascriptChannel(
      name: 'lkMsg', // 与h5 端的一致 不然收不到消息
      onMessageReceived: (JavascriptMessage message) async{
        print(message.message);
      });
  //FlutterWebviewPlugin flutterWebviewPlugin;
  ArticleCollectViewModel _articleCollectViewModel = serviceLocator<ArticleCollectViewModel>();
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
//    flutterWebviewPlugin = FlutterWebviewPlugin();
//    flutterWebviewPlugin.onStateChanged.listen((state){
//      if(state == WebViewState.startLoad){
//        setState(() {
//          isLoading = true;
//        });
//      }else if(state == WebViewState.finishLoad){
//        setState(() {
//          isLoading = false;
//        });
//      }
//    });

  }
  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    //flutterWebviewPlugin.dispose();
  }

  @override
  Widget build(BuildContext context) {
    bool isCollet = widget.webData.isCollect??false;
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.webData.title??"网页"),
        actions: <Widget>[
          Offstage(
            offstage: !widget.webData.isCanCollect,
            child: IconButton(
              icon: Icon(Icons.favorite),
              color: isCollet?Colors.red:Colors.grey,
              onPressed: _collect,
            ),
          )
        ],
        bottom: PreferredSize(
          preferredSize: Size.fromHeight(1.0),
          child: const LinearProgressIndicator(),
        ),
        bottomOpacity: isLoading?1.0:0,
      ),
      body: WebView(
        initialUrl: widget.webData.url,
        //userAgent:"your userAgent", // h5 可以通过navigator.userAgent判断当前环境
        javascriptMode: JavascriptMode.unrestricted, // 启用 js交互，默认不启用JavascriptMode.disabled
//        javascriptChannels: <JavascriptChannel>[
//          _JsBridge(context) // 与h5 通信
//        ].toSet()
        onWebViewCreated: (WebViewController controller){
          /// webview 创建调用，
          _webViewController = controller;
          controller.loadUrl(widget.webData.url);
          isLoading = true;
          controller.canGoBack().then((res){
            print(res);
          });
          controller.currentUrl().then((res){
            print(res);
          });
          controller.canGoForward().then((res){
            print(res);
          });
        },
        navigationDelegate: (NavigationRequest request){
          ///在页面跳转之前调用，TODO isForMainFrame为false,页面不跳转.导致网页内很多链接点击没效果
          bool isCanNavigate = true;
          if(!isCanNavigate) {

            return NavigationDecision.prevent; ///禁止跳转;
          }
          return NavigationDecision.navigate; ///跳转;
        },
        onPageFinished: (String value){
          ///webview 页面加载调用
          ///flutter 调用h5 端方法
//          _webViewController
//              .evaluateJavascript('document.title')
//              .then((title) {
//            // 获取网页title
//            print(title);
//          });
          setState(() {
            isLoading = false;
          });

        },
      ),
    );
  }
  _collect() async{
    var result;
    var isLogin = AppManager.isLogin();
    if(isLogin){
      if(widget.webData.isCollect){
        result = await _articleCollectViewModel.unCollectArticle(widget.webData.id);
      }else{
        result = await _articleCollectViewModel.collectArticle(widget.webData.id);
      }
    }else{
      Navigator.push(context, MaterialPageRoute(builder: (_){
        return LoginPage();
      }));
    }
    if(result){
      setState(() {
        widget.webData.isCollect = !widget.webData.isCollect;
        AppManager.eventBus.fire(CollectEvent(widget.webData.id,widget.webData.isCollect  ));
      });
      //_articleCollectViewModel.setArticleItemCollect(widget.webData);

    }
//    if(result != null){
//      if(result["errorCode"] == 0){
//        setState(() {
//          widget.webData.isCollect = !widget.webData.isCollect;
//          AppManager.eventBus.fire(CollectEvent(widget.webData.id,widget.webData.isCollect  ));
//        });
//      }
//    }
  }
}
